import Vue from 'vue'
import Vuex from 'vuex'
/*import mutations from "../../../HYMall-master/src/store/mutations";
import actions from "../../../HYMall-master/src/store/actions";
import getters from "../../../HYMall-master/src/store/getters";*/
Vue.use(Vuex)

const state = {
  cartList: []
}

const store = new Vuex.Store({
  state,
  mutations:{
    //mutations的方法功能唯一性
      addCounter(state,payload){
        payload.count+=1
        console.log(state.cartList)
      },
      addToCart(state,payload){
        state.cartList.push(payload)
        console.log(state.cartList)
      }
  },
  actions:{
    addCart(context,payload){
      return new Promise((resolve,reject)=>{
        /*    state.cartList.push(payload)
        console.log(state.cartList)*/
        //1  2  3
        let oldGoods = null;
        for (let item of context.state.cartList){
          if (item.iid===payload.iid){
            oldGoods = item
          }
        }
        // 上面的等价const oldInfo = state.cartList.find(item => item.iid === info.iid)
        if (oldGoods){
          // oldGoods.count+=1;
          context.commit('addCounter',oldGoods)
          resolve('当前商品数量+1')
        }
        else{
          //默认加入购物车
          payload.checked = true
          payload.count=1;
          // context.state.cartList.push(payload)
          context.commit('addToCart',payload)
          resolve('已经添加新的商品')
        }
      })

    }
},
  getters:{
    cartList(state) {
      return state.cartList
    },
    cartCount(state, getters) {
      return getters.cartList.length
    },
    cartAllGoodsCounts(state, getters) {
      return getters.cartList.filter((item)=>{
          return item.checked
        }).reduce((pre,cur)=>{
          return pre+cur.count
        },0)
    }
  }

})

export default store
